<template>
	<el-dialog :title="form.id ? '编辑项目' : '新增项目'" v-model="visible" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="120px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item label="项目名称" prop="name">
						<el-input v-model="form.name" placeholder="请输入项目名称" clearable />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="项目编号">
						<el-input v-model="form.code" placeholder="请输入项目编号" clearable disabled />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="所属年份" prop="year">
						<el-date-picker v-model="form.year" type="year" placeholder="请选择所属年份" value-format="YYYY"></el-date-picker>
						<!-- <el-select v-model="form.year" placeholder="请选择所属年份" clearable>
							<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in internal_project_type" />
						</el-select> -->
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="项目类型" prop="type">
						<el-select v-model="form.type" placeholder="请选择项目类型" clearable>
							<el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in internal_project_type" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="合同金额" prop="contractAmount">
						<el-input type="number" v-model="form.contractAmount" placeholder="请输入合同金额" clearable>
							<template v-slot:append>元</template>
						</el-input>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="利润率" prop="profitRate">
						<el-input type="number" v-model="form.profitRate" placeholder="请输入利润率" clearable>
							<template v-slot:append>%</template>
						</el-input>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="总控制成本" prop="costAmount">
						<el-input type="number" v-model="form.costAmount" placeholder="请输入总控制成本" clearable>
							<template v-slot:append>元</template>
						</el-input>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="排序" prop="sort">
						<el-input type="number" v-model="form.sort" placeholder="请输入排序" clearable> </el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-table
					ref="formTable"
					:data="filterCostTypeData"
					border
					stripe
					:cell-style="{ textAlign: 'center' }"
					:header-cell-style="{
						textAlign: 'center',
						background: 'var(--el-table-row-hover-bg-color)',
						color: 'var(--el-text-color-primary)',
					}"
					height="300"
					placeholder="暂无数据"
				>
					<el-table-column label="成本项名称" prop="name" show-overflow-tooltip>
						<template v-slot:header="scope">
							<el-input
								v-model="costTypeSearch"
								size="mini"
								placeholder="输入成本项名称搜索"
								clearable
								style="width: 60%"
								suffix-icon="el-icon-search"
							/>
						</template>
					</el-table-column>
					<el-table-column label="选择" prop="attrName" show-overflow-tooltip>
						<template #default="{ row }">
							<el-checkbox v-model="row.selected" :true-label="1" :false-label="0"></el-checkbox>
						</template>
					</el-table-column>
				</el-table>
			</el-row>
			<el-row style="margin-top: 10px">
				<sc-form-table ref="formTable1" v-model="filteredTableData" :hideAdd="true" :hideDelete="true" placeholder="暂无数据">
					<el-table-column label="年月" prop="attrName" show-overflow-tooltip>
						<template #default="{ row }">
							<el-date-picker v-model="row.yearMonth" type="month" placeholder="选择月" @change="monthChange(row)" value-format="YYYY-MM">
							</el-date-picker>
						</template>
					</el-table-column>
					<el-table-column label="月产值" prop="outputValue" show-overflow-tooltip>
						<template #default="{ row }">
							<el-input v-model="row.outputValue" placeholder="请输入月产值">
								<template v-slot:append>元</template>
							</el-input>
						</template>
					</el-table-column>
					<el-table-column label="月控制成本" prop="costLimit" show-overflow-tooltip>
						<template #default="{ row }">
							<el-input v-model="row.costLimit" placeholder="请输入月控制成本">
								<template v-slot:append>元</template>
							</el-input>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="120px">
						<template #default="{ row }">
							<el-button icon="delete" text type="primary" @click="onDelRow(row)">删除</el-button>
						</template>
					</el-table-column>
				</sc-form-table>
				<el-button v-if="filteredTableData.length < 12" type="text" @click="onAddRow">新增年月</el-button>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="IntProjectDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from '/@/hooks/message';
import { getObj, addObj, putObj, costTypeList } from '/@/api/internal/cost/intProject';
import { rule } from '/@/utils/validate';
import { computed } from 'vue';
const emit = defineEmits(['refresh']);

const scFormTable = defineAsyncComponent(() => import('/@/components/FormTable/index.vue'));

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const costTypeData = ref<any[]>([]);
const costTypeSearch = ref('');
// 定义字典
const { internal_project_type } = useDict('internal_project_type');

// 提交表单数据
const form = reactive({
	id: '',
	name: '',
	code: '',
	year: String(new Date().getFullYear()),
	type: '',
	contractAmount: '',
	profitRate: '',
	costAmount: '',
	costTypeIds: ref<any[]>([]),
	expectData: ref<any[]>([]),
	sort: null,
});

// 定义校验规则
const dataRules = ref({
	name: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
	year: [{ required: true, message: '所属年份不能为空', trigger: 'blur' }],
	type: [{ required: true, message: '项目类型不能为空', trigger: 'blur' }],
	contractAmount: [
		{ required: true, message: '合同金额不能为空', trigger: 'blur' },
		{ validator: rule.number, trigger: 'blur' },
	],
	profitRate: [
		{ required: true, message: '利润率不能为空', trigger: 'blur' },
		{ validator: rule.number, trigger: 'blur' },
	],
	costAmount: [
		{ required: true, message: '总控制成本不能为空', trigger: 'blur' },
		{ validator: rule.number, trigger: 'blur' },
	],
});

const filteredTableData = computed(() => {
	return form.expectData.filter((item) => item.delFlag == 0);
});

// 打开弹窗
const openDialog = (id: string) => {
	visible.value = true;
	form.id = '';

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
		form.expectData = [];
	});

	// 获取intProject信息
	if (id) {
		form.id = id;
		getintProjectData(id);
	}

	// 加载使用的数据
	getCostTypeData();
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		form.costTypeIds = [];
		form.costTypeIds = costTypeData.value.filter((item: any) => item.selected == 1).map((item: any) => item.id);
		loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 新增行
const onAddRow = async () => {
	form.expectData.push({ delFlag: 0 });
};

// 删除行
const onDelRow = (item: any) => {
	item.delFlag = 1;
};

// 初始化表单数据
const getintProjectData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj(id)
		.then((res: any) => {
			Object.assign(form, res.data);
		})
		.finally(() => {
			loading.value = false;
		});
};

// 获取成本项数据
const getCostTypeData = () => {
	costTypeList({ id: form.id }).then((res) => {
		costTypeData.value = res.data;
	});
};

// 月度选择
const monthChange = (item: any) => {
	const time = new Date(item.yearMonth);
	item.year = time.getFullYear();
	item.month = time.getMonth() + 1;
};

const filterCostTypeData = computed(() => {
	return costTypeData.value.filter((data) => !costTypeSearch.value || data.name.toLowerCase().includes(costTypeSearch.value.toLowerCase()));
});
// 暴露变量
defineExpose({
	openDialog,
});
</script>
